package com.fyzk.activity.forum;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tyjc.lottery.R;
import com.fyzk.utils.GlideUtils;
import com.fyzk.utils.LogUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import http.DataUtil.text.TextUtil;

/**
 * Created by fanxs11 on 17/5/12.
 */

public class TopicDetailAdapter extends BaseAdapter {
    private Context context;
    private TopicListBean headInfo;
    private List<TopicDetailBean> infos = new ArrayList<>();
    private OnCommentClcikListener onCommentClcikListener;

    public TopicDetailAdapter(Context context, List<TopicDetailBean> infos) {
        this.context = context;
        this.infos = infos;
    }

    @Override
    public int getCount() {
        return infos.size() + 1;
    }

    @Override
    public Object getItem(int position) {
        if (position > 0) {
            return infos.get(position-1);
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.adapter_topicdetail, null);
            holder.ll = (LinearLayout) convertView.findViewById(R.id.topicdetail_item_ll1);
            holder.ll2 = (RelativeLayout) convertView.findViewById(R.id.topicdetail_item_ll2);
            holder.ll3 = (LinearLayout) convertView.findViewById(R.id.topicdetail_item_ll3);
            holder.header_iv = (ImageView) convertView.findViewById(R.id.topicdetail_item_icon);
            holder.userName_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_username);
            holder.time_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_time);
            holder.title_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_title);
            holder.content_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_content);
            holder.imgs_ll = (LinearLayout) convertView.findViewById(R.id.topicdetail_item_imgs);

            holder.reply_comment_count_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_comment_count);

            holder.reply_header_iv = (ImageView) convertView.findViewById(R.id.topicdetail_item_reply_icon);
            holder.reply_userName_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_reply_username);
            holder.reply_time_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_reply_time);
            holder.reply_content_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_reply_content);

            holder.originalPoster_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_originalposter);
            holder.reply_floor_tv = (TextView) convertView.findViewById(R.id.topicdetail_item_floor);

            holder.comment_ll = (LinearLayout) convertView.findViewById(R.id.topicdetail_item_comment_ll);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (position == 0) {    // 头布局
            holder.ll.setVisibility(View.VISIBLE);
            holder.ll2.setVisibility(View.GONE);
            holder.ll3.setVisibility(View.GONE);

            if (headInfo != null) {
                Glide.with(context).load(headInfo.getUser_info()
                        .getAvatar_file())
                        .error(R.drawable.forum_header)
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .transform(new GlideUtils(context))
                        .into(holder.header_iv);
                if (TextUtil.isEmpty(headInfo.getUser_info().getAlias())) {
                    holder.userName_tv.setText(headInfo.getUser_info().getUser_name());
                } else {
                    holder.userName_tv.setText(headInfo.getUser_info().getAlias());
                }
                holder.time_tv.setText(getTimeStr(headInfo.getAdd_time()*1000));
                holder.title_tv.setText(headInfo.getQuestion_content());
                String html = getHtmlText(headInfo);
                if (html != null) {
                    holder.content_tv.setText(Html.fromHtml(html, new MImageGetter(holder.content_tv, context), null));
                }
            }
        } else {
            TopicDetailBean info = infos.get(position-1);
            if (position == 1) {
                holder.ll.setVisibility(View.GONE);
                holder.ll2.setVisibility(View.VISIBLE);
                holder.ll3.setVisibility(View.VISIBLE);
            } else {
                holder.ll.setVisibility(View.GONE);
                holder.ll2.setVisibility(View.GONE);
                holder.ll3.setVisibility(View.VISIBLE);
            }

            holder.reply_comment_count_tv.setText("全部评论 "+infos.size());
            if (null != info && null != info.getUser_info()) {
                Glide.with(context).load(info.getUser_info().getAvatar_file())
                        .error(R.drawable.forum_header)
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .transform(new GlideUtils(context)).into(holder.reply_header_iv);
                if (TextUtil.isEmpty(info.getUser_info().getAlias())) {
                    holder.reply_userName_tv.setText(info.getUser_info().getUser_name());
                } else {
                    holder.reply_userName_tv.setText(info.getUser_info().getAlias());
                }
                if (headInfo != null && info.getUser_info().getUser_name().equals(headInfo.getUser_info().getUser_name())) {
                    holder.originalPoster_tv.setVisibility(View.VISIBLE);
                } else {
                    holder.originalPoster_tv.setVisibility(View.GONE);
                }
            } else {
                LogUtil.d("info is null");
            }
            holder.reply_floor_tv.setText((position+1)+"楼");
            holder.reply_time_tv.setText(getTimeStr(info.getAdd_time()*1000));
            holder.reply_content_tv.setText(info.getAnswer_content());

            holder.comment_ll.removeAllViews();
            for (int i =0; i < info.getAnswer_comment().size(); i++) {
                boolean isOriginalPoster = false;
                if (headInfo != null && info.getAnswer_comment().get(i).getUser_name().equals(headInfo.getUser_info().getUser_name())) {
                    isOriginalPoster = true;
                }
                holder.comment_ll.addView(getComment(info.getAnswer_comment().get(i), isOriginalPoster, i < info.getAnswer_comment().size() - 1, (position+1)));
            }
        }

        return convertView;
    }

    public void setInfos(List<TopicDetailBean> infos) {
        this.infos = infos;
        this.notifyDataSetChanged();
    }

    public void setHeadInfo(TopicListBean headInfo) {
        this.headInfo = headInfo;
        this.notifyDataSetChanged();
    }

    private String getHtmlText(TopicListBean headInfo) {
        String text = headInfo.getQuestion_detail();
        String htmlText = "";
        if (text != null && text.contains("[attach]")) {
//            String textAndImages = text.replaceAll(".[attach].*[/attach].", " ☆ ");
            String[] contents = text.split("\\[/attach]");
            for (int i = 0; i < contents.length; i++) {
                String[] t_i = contents[i].split("\\[attach]");
                if (t_i[0] != null && !t_i[0].equals("")) {
                    htmlText += t_i[0];
                }
//                if (i < contents.length - 1) {
//                }
                if (i < headInfo.getImageBeens().size()) {
                    TopicListBean.ImageBean imageBean = headInfo.getImageBeens().get(i);
                    htmlText += "<img src='"+imageBean.attachment+"'/>";
                }
            }
        } else {
            htmlText = text;
        }
        if (htmlText != null && htmlText.contains("\n")) {
            htmlText = htmlText.replaceAll("\n", "\\<br/>");
        }
//        LogUtil.d("html:"+htmlText);
        return htmlText;
    }

    private LinearLayout getComment(final TopicDetailBean.AnswerCommentBean commentInfo, boolean isOriginalPoster, boolean isLine, final int floor) {
        LinearLayout ll = (LinearLayout) View.inflate(context,R.layout.layout_ll_topiccommentreply,null);
        TextView userName = (TextView) ll.findViewById(R.id.replay_name);
        TextView content = (TextView) ll.findViewById(R.id.replay_content);
        ll.setClickable(true);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onCommentClcikListener != null) {
                    onCommentClcikListener.onClick(commentInfo.getAnswer_id(),"@"+commentInfo.getAlias()+":",floor);
                }
            }
        });
        String originalPStr = isOriginalPoster ? " 楼主" : "";
        String alias = commentInfo.getAlias();
        if (TextUtil.isEmpty(alias)) {
            alias = commentInfo.getUser_name();
        }
        String userNameStr = String.format("<font color='#08578b'>%s</font><font color='#009dff'>%s</font><font color='#08578b'>:</font>", alias, originalPStr);
        userName.setText(Html.fromHtml(userNameStr));
        content.setText(commentInfo.getMessage());
        return ll;
    }

    private String getTimeStr(long time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
        return simpleDateFormat.format(new Date(time));
    }

    public void setOnCommentClcikListener(OnCommentClcikListener onCommentClcikListener) {
        this.onCommentClcikListener = onCommentClcikListener;
    }

    class ViewHolder{
        LinearLayout ll;        // 展示帖子详情
        RelativeLayout ll2;     // 展示回复数量
        LinearLayout ll3;       // 展示回复内容
        ImageView header_iv;
        TextView userName_tv;
        TextView time_tv;
        TextView title_tv;
        TextView content_tv;
        LinearLayout imgs_ll;

        TextView reply_comment_count_tv;    // 帖子评论数量

        ImageView reply_header_iv;
        TextView reply_userName_tv;
        TextView reply_time_tv;
        TextView reply_content_tv;
        TextView originalPoster_tv;     // 是否是楼主
        TextView reply_floor_tv;        // 楼层

        LinearLayout comment_ll;    // 展示评论
    }
}

interface OnCommentClcikListener {
    void onClick(int answer_id, String userName, int floor);
}
